const { querySql, queryOne } = require("../utils/dbUtils");
const commonUtils = require("../utils/commonUtils");
const jwt = require("jsonwebtoken");
const boom = require("boom");
const { body, validationResult } = require("express-validator");
const { decode } = require("../utils/user-jwt"); // 引入jwt认证函数
const {
  CODE_ERROR,
  CODE_SUCCESS,
  PRIVATE_KEY,
  JWT_EXPIRED,
} = require("../utils/constant");

// 查询工具列表
function getToolsList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回
    next(boom.badRequest(msg));
  } else {
    // let { pageSize, pageNo, status } = req.query;
    // // 默认值
    // pageSize = pageSize ? pageSize : 1;
    // pageNo = pageNo ? pageNo : 1;
    // status = status || status == 0 ? status : null;
    // console.log("aaa="+JSON.stringify());
    let tokenInfo = decode(req);
    let username = tokenInfo.username;

    let query = `select d.id, d.title, d.icon, d.description, d.url from tb_tools d`;
    querySql(query).then((data2) => {
      // console.log('任务列表查询===', data);
      if (!data2 || data2.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "暂无数据",
          data: null,
        });
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: "查询数据成功",
          data: {
            list: data2,
            username: username,
          },
        });
      }
    });
  }
}

// 添加工具
function addTools(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { title, icon, description, url } = req.body;
    findTools(title, 1).then((task) => {
      if (task) {
        res.json({
          code: CODE_ERROR,
          msg: "工具名称不能重复",
          data: null,
        });
      } else {
        const query = `insert into tb_tools(title, icon, description, url) values('${title}', '${icon}', '${description}', '${url}')`;
        querySql(query).then((data) => {
          // console.log('添加任务===', data);
          if (!data || data.length === 0) {
            res.json({
              code: CODE_ERROR,
              msg: "添加数据失败",
              data: null,
            });
          } else {
            res.json({
              code: CODE_SUCCESS,
              msg: "添加数据成功",
              data: {},
            });
          }
        });
      }
    });
  }
}

// 编辑工具
function editTools(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id, title, icon, description, url } = req.body;
    findTools(id, 2).then((task) => {
      if (task) {
        findTools(title, 1).then((result) => {
          if (result) {
            res.json({
              code: CODE_ERROR,
              msg: "工具名称不能重复",
              data: null,
            });
          } else {
            const query = `update tb_tools set title='${title}', icon='${icon}', description='${description}', url='${url}' where id='${id}'`;
            querySql(query).then((data) => {
              // console.log('编辑任务===', data);
              if (!data || data.length === 0) {
                res.json({
                  code: CODE_ERROR,
                  msg: "更新数据失败",
                  data: {},
                });
              } else {
                res.json({
                  code: CODE_SUCCESS,
                  msg: "更新数据成功",
                  data: {},
                });
              }
            });
          }
        });
      } else {
        res.json({
          code: CODE_ERROR,
          msg: "参数错误或数据不存在",
          data: null,
        });
      }
    });
  }
}

// // 删除工具
// function deleteTools(req, res, next) {
//   const err = validationResult(req);
//   if (!err.isEmpty()) {
//     const [{ msg }] = err.errors;
//     next(boom.badRequest(msg));
//   } else {
//     let { id, status } = req.body;
//     findTools(id, 2).then((task) => {
//       if (task) {
//         const query = `update sys_task set status='${status}' where id='${id}'`;
//         // const query = `delete from sys_task where id='${id}'`;
//         querySql(query).then((data) => {
//           // console.log('删除任务===', data);
//           if (!data || data.length === 0) {
//             res.json({
//               code: CODE_ERROR,
//               msg: "删除数据失败",
//               data: null,
//             });
//           } else {
//             res.json({
//               code: CODE_SUCCESS,
//               msg: "删除数据成功",
//               data: null,
//             });
//           }
//         });
//       } else {
//         res.json({
//           code: CODE_ERROR,
//           msg: "数据不存在",
//           data: null,
//         });
//       }
//     });
//   }
// }

// 获取用户列表
function getUserList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回
    next(boom.badRequest(msg));
  } else {
    // let { pageSize, pageNo, status } = req.query;
    // // 默认值
    // pageSize = pageSize ? pageSize : 1;
    // pageNo = pageNo ? pageNo : 1;
    // status = status || status == 0 ? status : null;
    // console.log("aaa="+JSON.stringify());
    let tokenInfo = decode(req);
    let username = tokenInfo.username;

    let query = `select d.id, d.username, d.nickname, d.avatar, d.description, d.isManager, d.registrationTime from tb_user d`;
    querySql(query).then((data2) => {
      // console.log('任务列表查询===', data);
      if (!data2 || data2.length === 0) {
        res.json({
          code: CODE_SUCCESS,
          msg: "",
          data: [],
        });
      } else {
        res.json({
          code: CODE_SUCCESS,
          msg: "",
          data: {
            list: data2,
            username: username,
          },
        });
      }
    });
  }
}

// 搜索用户
function searchUser(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { keyWord } = req.body;

    if (keyWord) {
      let query = `select d.id, d.username, d.nickname, d.avatar, d.description, d.isManager, d.registrationTime from tb_user d where username='${keyWord}'`;
      querySql(query).then((data2) => {
        // console.log('点亮红星标记===', data);
        if (!data2 || data2.length === 0) {
          res.json({
            code: CODE_ERROR,
            msg: "搜索数据失败",
            data: null,
          });
        } else {
          res.json({
            code: CODE_SUCCESS,
            msg: "搜索成功",
            data: {
              list: data2,
            },
          });
        }
      });
    } else {
      res.json({
        code: CODE_SUCCESS,
        msg: "搜索成功",
        data: {
          list: [],
        },
      });
    }
  }
}

// 添加管理员
function addManager(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let tokenInfo = decode(req);
    let localusername = tokenInfo.username;

    let query = `select d.id, d.username, d.nickname, d.avatar, d.description, d.isManager, d.registrationTime from tb_user d where username='${localusername}'`;
    querySql(query).then((data2) => {
      // console.log('任务列表查询===', data);
      if (!data2 || data2.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "你登录的账号不存在",
          data: [],
        });
      } else {
        if (1 === Number(data2[0].isManager)) {
          let { username } = req.body;
          if (username) {
            const query = `update tb_user set isManager= 1 where username='${username}'`;
            querySql(query).then((data) => {
              // console.log('点亮红星标记===', data);
              if (!data || data.length === 0) {
                res.json({
                  code: CODE_ERROR,
                  msg: "操作数据失败",
                  data: {},
                });
              } else {
                res.json({
                  code: CODE_SUCCESS,
                  msg: "操作数据成功",
                  data: {},
                });
              }
            });
          } else {
            res.json({
              code: CODE_ERROR,
              msg: "参数错误或数据不存在",
              data: {},
            });
          }
        } else {
          res.json({
            code: CODE_ERROR,
            msg: "你登录的账号没有添加管理员的权限",
            data: {},
          });
        }
      }
    });
  }
}

// 登录
function adminLogin(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回
    next(boom.badRequest(msg));
  } else {
    let { username, password } = req.body;
    // md5加密
    password = commonUtils.md5(password);
    const query = `select * from tb_user where username='${username}' and password='${password}'`;
    querySql(query).then((user) => {
      // console.log('用户登录===', user);
      if (!user || user.length === 0) {
        res.json({
          code: CODE_ERROR,
          msg: "用户名或密码错误",
          data: null,
        });
      } else {
        if (1 === Number(user[0].isManager)) {
          // 登录成功，签发一个token并返回给前端
          const token = jwt.sign(
            // payload：签发的 token 里面要包含的一些数据。
            { username },
            // 私钥
            PRIVATE_KEY,
            // 设置过期时间
            { expiresIn: JWT_EXPIRED }
          );

          let userData = {
            id: user[0].id,
            username: user[0].username,
            nickname: user[0].nickname,
            avator: user[0].avator,
            // sex: user[0].sex,
            registrationtime: user[0].registrationtime,
            lastlogintime: user[0].lastlogintime,
          };

          res.json({
            code: CODE_SUCCESS,
            msg: "登录成功",
            data: {
              token,
              userData,
            },
          });
        } else {
          res.json({
            code: CODE_ERROR,
            msg: "该用户不是管理员",
            data: null,
          });
        }
      }
    });
  }
}

// 通过工具名称或ID查询数据是否存在
function findTools(param, type) {
  let query = null;
  if (type == 1) {
    // 1:添加类型 2:编辑或删除类型
    query = `select id, title from tb_tools where title='${param}'`;
  } else {
    query = `select id, title from tb_tools where id='${param}'`;
  }
  return queryOne(query);
}

module.exports = {
  getToolsList,
  addTools,
  editTools,
  // deleteTools,
  getUserList,
  searchUser,
  addManager,
  adminLogin,
};
